package db

import (
	"main/middlewares/public/models"
	"main/middlewares/public/tools"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"net/url"
	"os"
	"time"
)

var DbUser *gorm.DB
var DbService *gorm.DB
var DbSQL  = DbService
func ConnectDB() {
	dbHost := tools.Conf.Get("db_host")
	dbPort := tools.Conf.Get("db_port")
	dbUser := tools.Conf.Get("db_user")
	dbPass := tools.Conf.Get("db_pass")
	dbNameUser := tools.Conf.Get("db_name_user")
	dbNameService := tools.Conf.Get("db_name_service")
	DsnUser := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&loc=%s&parseTime=true",
		dbUser,
		dbPass,
		dbHost,
		dbPort,
		dbNameUser,
		url.QueryEscape("Asia/Shanghai"),
	)

	DsnService := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&loc=%s&parseTime=true",
		dbUser,
		dbPass,
		dbHost,
		dbPort,
		dbNameService,
		url.QueryEscape("Asia/Shanghai"),
	)


	var err error
	DbUser, err = gorm.Open("mysql", DsnUser)
	if err != nil {
		fmt.Println("database connect error:", err)
		os.Exit(0)
	}
	DbService, err = gorm.Open("mysql", DsnService)
	if err != nil {
		fmt.Println("database connect error:", err)
		os.Exit(0)
	}

	DbUser.SingularTable(true)
	DbUser.DB().SetMaxOpenConns(100)
	DbUser.DB().SetMaxIdleConns(20)
	DbUser.DB().SetConnMaxLifetime(time.Minute)
	DbService.SingularTable(true)
	DbService.DB().SetMaxOpenConns(100)
	DbService.DB().SetMaxIdleConns(20)
	DbService.DB().SetConnMaxLifetime(time.Minute)

	if tools.Conf.Get("debug") == "true" {
		DbUser = DbUser.Debug()
		DbService = DbService.Debug()
	}



	fmt.Println("database connect success")
}

func SyncDB() {
	ConnectDB()
	DbSQL.Debug().Set("gorm:table_options", "ENGINE=InnoDB").
		AutoMigrate(
			&models.Columns{},
			&models.System{},
			&models.User{},
			&models.Machine{},
			&models.Worker{},
			&models.Record{},
			&models.Seed{},
			&models.NsqSetting{},
		)

	os.Exit(0)
}
func TableName(name string) string {
	return tools.Conf.Get("db_prefix") + name
}